<?php

namespace app\web\controller;

use think\Db;
use app\model\Users as UserModel;
use think\Session;
use think\Validate;
use think\Request;

class Login extends Base
{
    public function login()
    {
        global $_P;
        $do = 'login';
        $op = !empty($_P['op']) ? $_P['op'] : 'home';
        switch ($op) {
            case 'home':
                return $this->home();
                break;
            case 'logout':
                return $this->logout();
                break;
            default:
                return $this->home();
                break;
        }
    }

    public function home()
    {
        global $_P, $_G;

        if ($_G['companyname'] == '易宣软件') {
            $home_img = 'http://css2020.yixuan.net/2020css/login_bg.jpg';
        } elseif ($_G['companyname'] == '飞驰软件') {
            $home_img = 'http://cdn.xjpf.net/images/global/a3wp33vpptV7GPmU3DE7TP3IpDtUt3.jpg/99.jpg';
        } elseif ($_G['companyname'] == '联登科技') {
            $home_img = 'http://liandeng.jiemeo.com/images/global/QNNqHyG92yXHeGeHv02VhlMGHVXQhy.jpg/99.jpg';
        } elseif ($_G['companyname'] == '领泽新营销') {
            $home_img = 'http://cdn.zuanla.net//images/global/DxIdXEx6yLOF5x33W338tO55L6dkDd.jpeg';
        } elseif ($_G['companyname'] == '金策软件') {
            $home_img = 'http://img2019.yixuansoft.cn/images/global/c2X08N0c646ZJJ6HjxO35sx20H26sx.jpg/99.jpg';
        } else {
            $home_img = 'http://img2019.yixuansoft.cn/images/global/gdxPsp0TsTuU9MsriALDR9RT9RS2St.jpeg';
        }
        $post_url = "/login.php?referer={$_P['referer']}";
        if (request()->isAjax()) {
            return $this->post_login();
        } else {
            $end_time = strtotime(date('Y-m-d', time()) . ' 23:59:59');
            if ($_COOKIE['username'] && $_COOKIE['single']) {
                $post['username'] = $_COOKIE['username'];
                $post['single'] = $_COOKIE['single'];
                $url = 'https://oa.yixuan.net/web/single.php';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                $result = curl_exec($ch);
                curl_close($ch);
                $res_array = json_decode($result, true);
                if ($res_array['code'] == 0) {
                    setcookie("autologin", 1, $end_time);
                    $_P['username'] = $res_array['data']['username'];
                    $_P['password'] = $res_array['data']['password'];
                    $_P['autologin'] = 1;
                    $this->post_login();
                } else {
                    setcookie("autologin", 0, $end_time);
                }
            } else {
                setcookie("autologin", 0, $end_time);
            }
            return view('/login', [
                '_G' => $_G,
                'referer' => $_P['referer'],
                'home_img' => $home_img,
                'post_url' => $post_url
            ]);
        }
    }

    public function post_login()
    {
        global $_P, $_G;
        $data['username'] = $_P['username'];
        $data['password'] = $_P['password'];
        $rule = [
            'username' => 'require|max:25',
            'password' => 'require|max:25',
        ];
        $msg = [
            'username.require' => '用户名不可为空',
            'username.max' => '用户名最多不能超过25个字符',
            'password.require' => '密码不可为空',
            'password.max' => '密码最多不能超过25个字符'
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->return_ajax_json(0, $validate->getError());
        }
        //判断用户
        $user = Db::table('yx_sys_users')->where('username', $_P['username'])->find();
        if (!$user) {
            $this->return_ajax_json(0, '用户不存在');
        }

        if (!$_P['autologin']) {
            if ($user['fail_count'] > 5 && $user['fail_last_time'] > time() - 300) {
                $this->return_ajax_json('-1', '密码错误超过5次，请在5分钟后再尝试');
            }
        }
        if ($user['fail_count'] > 0 && $user['fail_last_time'] < time() - 300) {    //超过五分钟清除错误次数
            Db::table('yx_sys_users')->where('id', $user['id'])->update(['fail_count' => 0, 'fail_last_time' => 0]);
        }

        //判断密码
        $postPassword = UserModel::userHash($data['password'], $user['salt']);
        if ($postPassword != $user['password']) {
            if (!$_P['autologin']) {
                //增加错误次数
                Db::table('yx_sys_users')->where('id', $user['id'])->setInc('fail_count');
                //更新错误时间
                Db::table('yx_sys_users')->where('id', $user['id'])->setField('fail_last_time', time());
            }
            $this->return_ajax_json(0, '密码错误');
        }

        if ($user['status'] == 0) {
            $this->return_ajax_json(0, '用户被禁用');
        }

        //判断账号是否已到期
        if ($user['endtime'] > 0 && $user['endtime'] < time()) {
            $this->return_ajax_json(0, '账号已到期');
        }

        if ($user['user_level'] > 2 && empty($user['module_name'])) {
            $this->return_ajax_json(0, '账号未绑定模块');
        }
        //保存session
        $_G['userid'] = $user['id'];
        $_G['userlevel'] = $user['user_level'];
        $_G['username'] = $user['username'];
        $_G['realname'] = $user['realname'];

        $update_data['lastvisit'] = time();
        Db::table('yx_sys_users')->where('id', $user['id'])->update($update_data);
        $user_session = [
            'userid' => $user['id'],
            'username' => $user['username'],
            'user_level' => $user['user_level'],
            'realname' => $user['realname']
        ];
        if ($user['user_level'] > 2) {
            $user_session['module_name'] = $user['module_name'];
            $_P['referer'] = createWebUrl('theme', array('op' => 'display', 'cw' => 'home', 'm' => $user['module_name']));
        }
        Session::set('userinfo', $user_session);
        if (!empty($_P['referer'])) {
            Session::set('referer', $_P['referer']);
        }

        $isSuperAdmin = ($user['user_level'] == 1 || $user['user_level'] == 2) ? 1 : 0;
        $forward = $_G['url_domain'] . '/web/index.php?c=account&a=display';
        if ($isSuperAdmin == 1 && !$_P['autologin']) {
            $token_salt = strtoupper(substr(md5($user['username'] . '_' . date('Ymd') . '_postOaLogin@yixuan.net'), 10, 10));
            $token = authcode($data['password'], 'ENCODE', $token_salt, 0);
            $post_data['username'] = $user['username'];
            $post_data['token'] = $token;
            $post_data['op'] = 'login';
            $post_data['res_url'] = $forward;
            $post_url = 'https://oa.yixuan.net/web/single.php';
            $oa_res = yxcurl($post_url, $post_data, '', true);
            if ($oa_res['code'] == 0) {
                $end_time = strtotime(date('Y-m-d', time()) . ' 23:59:59');
                setcookie("autologin", 1, $end_time);
                $res['redirect'] = $oa_res['data']['forward'];
            } else {
                $res['redirect'] = $forward;
                //yxlog($oa_res['msg'], '账号同步登录');
            }
            $this->return_ajax_json(1, '登录成功', $res);
        } elseif ($isSuperAdmin == 1 && $_P['autologin'] == 1) {
            return true;
        } else {
            $res['redirect'] = $forward;
            $this->return_ajax_json(1, '登录成功', $res);
        }
    }

    //退出登录
    public function logout()
    {
        global $_P, $_G;
        $forward = $_G['url_domain'] . 'login.php';
        if ($_G['isSuperAdmin'] && $_COOKIE['autologin']) {
            $this->clean_cookie();
            $res_url = urlencode($forward);
            $url = "https://oa.yixuan.net/web/single.php?res_url={$res_url}&op=loginout&username={$_G['username']}";
            echo "<script>window.location.href='$url';</script>";
        }
        Session::delete('userinfo');
        exit("<script>window.location.href = '{$forward}';</script>");
    }

    public function route()
    {
        $forward = Session::get('referer');
        if (empty($forward) || $forward == '/web/index.php') {
            $user = Session::get('userinfo');
            if ($user['user_level'] > 2) {
                $module = $user['module_name'];
                $forward = createWebUrl('theme', array('op' => 'display', 'cw' => 'home', 'm' => $module));
            } else {
                $forward = createWebUrl('yxmodule', ['op' => 'display'], true);
            }
        }
        $this->redirect($forward);
    }

    public function clean_cookie()
    {
        $end_time = strtotime(date('Y-m-d', time()) . ' 23:59:59');
        $cookie_url = substr($_SERVER['HTTP_HOST'], stripos($_SERVER['HTTP_HOST'], '.'));
        setcookie("username", '', -3600, "/", "$cookie_url");
        setcookie("single", '', -3600, "/", "$cookie_url");
        setcookie("singlestatus", 0, $end_time, "/", $cookie_url);
    }

}